<?php
class controller_UserController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {
        //первым делом проверяем, админ ли пытается перейти к этому разделу
        //если нет, то выгоняем его отсюда
        $user = model_UserMapper::getCurrentUser();
        if(null == $user->getId()) {
            $this->view->message = 'У вас нет доступа к этой функции!';
            $this->view->setRenderTemplate("error.phtml");
            return;
        } else {

            if(empty($this->args['action'])) {
                $this->index();
            } else {
                switch ($this->args['action']) {

                    case 'index':
                        $this->index();
                        break;

                    case 'edit':
                        $this->edit();
                        break;

                    case 'save':
                        $this->save();
                        break;

                    case 'delete':
                        if('admin' != $user->getRole()) {
                            $this->view->message = 'У вас нет доступа к этой функции!';
                            $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                            $this->view->setRenderTemplate("error.phtml");
                        } else {
                            $this->delete();
                        }
                        break;

                    case 'ban':
                        if('admin' != $user->getRole()) {
                            $this->view->message = 'У вас нет доступа к этой функции!';
                            $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                            $this->view->setRenderTemplate("error.phtml");
                        } else {
                            $this->ban();
                        }
                        break;

                    case 'unban':
                        if('admin' != $user->getRole()) {
                            $this->view->message = 'У вас нет доступа к этой функции!';
                            $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                            $this->view->setRenderTemplate("error.phtml");
                        } else {
                            $this->unban();
                        }
                        break;

                    case 'setAvatar':
                        $this->setAvatar();
                        break;

                    case 'saveAvatar':
                        $this->saveAvatar();
                        break;

                    default:
                        $this->index();
                }
            }
        }
    }

    public function edit() {
        if (!empty($this->args['id'])) {
            $user = model_UserMapper::getCurrentUser();

            if ($user->getId() == $this->args['id']) {
                $mapper = new model_UserMapper();
                $photoMapper = new model_PhotoMapper();

                $this->view->oneModel = $mapper->find($this->args['id']);
                $this->view->allImgs = $photoMapper->fetchAll($this->args['id']);

                $this->view->setRenderTemplate("user/edit.phtml");

            } else {
                $this->view->message = 'Отказано в доступе!';
                $this->view->link = '<p><a href="?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
            }
        } else {
            $this->view->link = 'index.php?controller=user';
            $this->view->setRenderTemplate("redirect.phtml");
        }

    }

    public function save() {

        $user = model_UserMapper::getCurrentUser();
        $post = model_ConfigMapper::validate($_POST);

        if ($user->getId() == $post['id']) {

            $mapper = new model_UserMapper();
            $model = new model_UserModel();

            if (!empty($post['password'])) {
                $salt = $user->getSalt();
                $password = md5($salt.$post['password']);

                if ($password == $user->getPassword()) {
                    if ( '' != $post['newpassword'] && $post['newpassword'] == $post['newrpassword']) {
                        $salt = model_ConfigMapper::getSalt(10);
                        $password = md5($salt.$post['newpassword']);

                        $model->setPassword($password)
                                ->setSalt($salt);

                    } else {
                        $this->view->message .= 'Пароли не совпадают!';
                        $this->view->setRenderTemplate("user/edit.phtml");
                        return;
                    }

                } else {
                    $this->view->message .= 'Вы указали неверный пароль!';
                    $this->view->setRenderTemplate("user/edit.phtml");
                    return;
                }
            }

            if(!empty($post['name']) || !empty($post['surname']) || !empty($post['avatar']) || !empty($post['about']) || !empty($post['age'])) {

                $salt = model_ConfigMapper::getSalt(10);
                $password = md5($salt.$post['password']);

                $model->setName($post['name'])
                        ->setSurname($post['surname'])
                        ->setAbout($post['about'])
                        ->setAvatar($post['avatar'])
                        ->setAge($post['age']);


            } else {
                $this->view->message .= 'Вы не изменили ни одного параметра!';
                $this->view->setRenderTemplate("user/edit.phtml");
                return;
            }
            
            $model->setId($post['id']);

            if ('' != $_FILES['file']['name']) {

                $uploaddir = 'stuff/images/saved/';
                $filename = model_ConfigMapper::getSalt(10);
                $uploadfile = $uploaddir.basename($filename);

                if ( false == move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile.'.jpg')) {
                    $this->view->message = 'Ошибка при загрузке файла!';
                    $this->view->oneModel = new model_UserModel();
                    $this->view->oneModel->setName($post['name'])
                            ->setSurname($post['surname'])
                            ->setAge($post['age']);
                    $this->view->setRenderTemplate("user/edit.phtml");
                    return;
                }
                $photoMapper = new model_PhotoMapper();
                $photoModel = new model_PhotoModel();
                $photoModel->setTitle(null)
                        ->setName($filename)
                        ->setOwner($user->getId());

                $photoMapper->save($photoModel);
                $post['avatar'] = mysql_insert_id();
            }
            
            $mapper->save($model);
            $mapper->saveAvatar($post['avatar'], $post['id']);

            $this->view->link = '?controller=user&action=index&id='. $user->getId() ;
            $this->view->setRenderTemplate("redirect.phtml");
            return;
        }
        else {
            $this->view->message = 'Ошибка запроса!';
            $this->view->link = '<p><a href="?controller=user&action=index&id='. $user->getId() .'">Моя страница</a></p>';
            $this->view->setRenderTemplate("error.phtml");
        }
    }

    public function index() {
        $mapper = new model_UserMapper();
        if(empty($this->args['id'])) { //если id пустой, то отрисовывем все новости (fetchAll)

            $nums = 5; // количество постов на страницу
            $pages = model_ConfigMapper::getPages($nums, $mapper->getTable()); //узнаем количество страниц

            if (!empty($this->args['page'])) { //проверка, какая страница указана
                if (1 > $this->args['page']) {
                    $page = 1;
                } elseif($this->args['page']>$pages) {
                    $page = $pages;
                } else {
                    $page = $this->args['page'];
                }
            } else {
                $page = 1;
            }

            $start = ($page - 1)* $nums;

            $this->view->allModels = $mapper->fetchAll($start, $nums);
            
            $link = 'controller=user&action=index';
            $this->view->paginator = model_ConfigMapper::getPaginator($page, $pages, $link);
            $this->view->setRenderTemplate("user/userFetchAll.phtml");

        } else { //если же нет, то ищем новость с этим id
            $this->view->oneModel = $mapper->find($this->args['id']);
            if(0 != $this->view->oneModel->getId()) {
                $this->view->setRenderTemplate("user/userFind.phtml");

            } else {
                $this->view->message = 'Такого пользователя нет!';
                $this->view->setRenderTemplate("error.phtml");
            }
        }
    }

    public function delete() {

        $mapper = new model_UserMapper();
        if(!empty($this->args['id'])) {
            if(1 == $this->args['id']) {
                $this->view->message = 'Вы не можете удалить самого себя, лол!';
                $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
            $mapper->delete($this->args['id']);
        }
        $this->view->link = 'index.php?controller=user';
        $this->view->setRenderTemplate("redirect.phtml");
    }

    public function ban() {
        $mapper = new model_UserMapper();
        if(!empty($this->args['id'])) {
            if(1 == $this->args['id']) {
                $this->view->message = 'Вы не можете забанить самого себя, лол!';
                $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
            $user = $mapper->find($this->args['id']);
            if('banned' != $user->getRole()) {
                $mapper->ban($this->args['id']);
            } else {
                $this->view->message = 'Этот пользователь и так забанен!';
                $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
        }
        $this->view->link = 'index.php?controller=user&action=index&id='. $this->args['id'];
        $this->view->setRenderTemplate("redirect.phtml");
    }

    public function unban() {
        $mapper = new model_UserMapper();
        if(!empty($this->args['id'])) {
            if(1 == $this->args['id']) {
                $this->view->message = 'Вы не можете забанить самого себя, лол!';
                $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
            $user = $mapper->find($this->args['id']);
            if('banned' == $user->getRole()) {
                $mapper->unban($this->args['id']);
            } else {
                $this->view->message = 'Этот пользователь и так разбанен!';
                $this->view->link = '<p><a href="index.php?controller=user">Ко всем юзерам</a></p>';
                $this->view->setRenderTemplate("error.phtml");
                return;
            }
        }
        $this->view->link = 'index.php?controller=user&action=index&id='. $this->args['id'];
        $this->view->setRenderTemplate("redirect.phtml");
    }

    public function setAvatar() {
        $user = model_UserMapper::getCurrentUser();
        $mapper = new model_PhotoMapper();
        $this->view->allImgs = $mapper->fetchAll($user->getId());

        if (empty($this->view->allImgs)) {
            $this->view->message = 'У вас ещё нет ни одной фотографии, что бы выбрать аватар';
            $this->view->link = '<p><a href="index.php?controller=photo&action=edit">Загрузить фотографию</a></p>';
            $this->view->setRenderTemplate("error.phtml");
        } else {
            $this->view->setRenderTemplate("user/setAvatar.phtml");
        }
    }

    public function saveAvatar() {
        $user = model_UserMapper::getCurrentUser();
        $post = model_ConfigMapper::validate($_POST);

        $mapper = new model_UserMapper();
        $mapper->saveAvatar($post['avatar'], $user->getId());

        $this->view->link = 'index.php?controller=user&action=index&id='. $user->getId();
        $this->view->setRenderTemplate("redirect.phtml");
    }
}